import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
      baseURL: 'http://localhost:8891/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 只有在非登录相关接口的401错误才跳转到登录页
    if (error.response?.status === 401) {
      const currentPath = window.location.pathname
      const isAuthRequest = error.config?.url?.includes('/auth/')
      
      // 如果不是在登录页面且不是认证相关请求，才跳转到登录页
      if (!isAuthRequest && currentPath !== '/login' && currentPath !== '/') {
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return
      }
    }
    
    // 直接抛出错误，让组件处理
    return Promise.reject(error)
  }
)

// 登录
export const login = (username, password) => {
  return api.post('/auth/login', { username, password })
}

export default api 